import random

from concepts.attributes import Attribute, _
from concepts.space import DIRECTIONS

from .building import Building
from .seeker import Seeker


class Walker(Seeker):
    distance  =_ (50)
    direction =_ (None)
    roadbound =_ (True)
    
    walked = Attribute(initial = 0, writable = True)
    
    def waiting(self):
        if not self.home.exists:
            self.destroy()
            return
        
        if self.has_arrived:
            self.on_arrival()
            return
        
        if self.walked >= self.distance:            
            self.walked = 0
            self.target = self.home
            
        if self.has_path:
            self.follow_path()
        else:
            self.walk()
    
    def walk(self):
        self.walked += 1
        
        directions = set(direction for direction in DIRECTIONS
                         if self.tile.in_direction(direction).is_walkable)
        
        if len(directions) > 1 and self.direction is not None:
            directions.discard(self.direction.reverse)
        
        if not directions:
            return
        
        self.direction = random.choice(list(directions))
        self.step      = self.position.in_direction(self.direction)
    
    def on_arrival(self):
        self.destroy()
